--[[
-- Author:      feilong
-- DateTime:    2018-04-23 17:19:33
-- Description: 配置读取服务
local service = g.newservice("config/config_service")
--设置共享数据
test.lua
return {
 a = { 
     aa=1
 },
 b = {
     bb=2
 }
}
--计取共享数据
local data = g.getConfig("test","a")
g.log:debug(data)

--]]


local lfs = require("lfs")

local table_insert = table.insert
local table_remove = table.remove

---------------------------------------------------------
-- class
---------------------------------------------------------
local Service = class("Config")

function Service:ctor(name)
	self.configs = {} --所有配置
	self:register()
end

function Service:register()
	g.register('start', handler(self, self.onStart))
	g.register('close', handler(self, self.onClose))

	g.register('load', handler(self, self.onLoad))
	g.register('reload', handler(self, self.onReload))
	g.register('get', handler(self, self.onGet))
	g.register('set', handler(self, self.onSet))
end

function Service:onStart()
	print("Config Service:onStart ")
	self:loadFromLocal()
	--测试热更
	-- skynet.fork(function()
	-- 	while true do
	-- 		skynet.sleep(500)
	-- 		self:test()
	-- 	end
	-- end)
end

function Service:onClose()
	print("Config Service:onClose")
end

--从本地加载配置文件
function Service:loadFromLocal()
	local config_path = g.getenv("root") .. "config/" --配置文件所在目录
	local file_list = {} --文件列表
	--for filename in lfs.dir(config_path) do
	--	if filename:find('%.lua$') and filename ~= "skynet.config" then
	--		table_insert(file_list,{
	--			path = config_path .. '/' .. filename,
	--			name = filename
	--		})
	--	end
	--end

	--要加到服务的配置文件， 还是手动写比较好
	file_list = {
		"room_cfg.lua",
		"texas_match_award_cfg.lua" ,
	}


	for _, file_name in ipairs(file_list) do
		local s = file_name
		local key = s:sub(1,-s:reverse():find('%.') - 1) --文件名作为key
		local path = config_path..file_name
		local data = dofile(path)
		self.configs[key] = data
		--print("_____->", s, tostring(data))
	end
end

--加载共享的配置(table 可以来自网络)
function Service:onLoad(configs)
	self:loadFromLocal()
	for key, conf in pairs(configs) do
		self.configs[key] = conf
	end
end

--收到别的服务器注册
function Service:onReload()
	g.log:debug("onReload hot_configs")
	self:loadFromLocal()
end

--取配置
function Service:onGet(file_name, key1)
	local data = self.configs[file_name] or {}
	--print("get config:", file_name, key1, tostring(self.configs[file_name]))
	if key1 then
		return data[key1]
	end
	return data
end

function Service:onSet(file_name, data)
	--print("set config:", file_name, tostring(data))
	self.configs[file_name] = data
end

function Service:test()
	print("____66666666___test___1", self:getObjName(), self:getObjId())

end

function Service:getObjTest()
	print("getObjTest")
end

return Service